package chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{
    DatagramSocket socket =null;
    private int port;
    private String msgfrom;

    public TalkReceive(int port, String msgfrom) {
        this.port = port;
        this.msgfrom = msgfrom;

        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while(true){
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                //阻塞式接收
                socket.receive(packet);
                //断开连接
                //将接收包转换为 String 格式
                byte[] data = packet.getData();
                String receiveData = new String(data,0,data.length);
                System.out.println(msgfrom+":"+receiveData);
                if (receiveData.equals("bye")){
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        socket.close();
    }
}
